import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import {
  ShootMode,
  Row,
  ShipType,
  type WeaopnModel,
  type ModelFleet,
  type ModelShipGroup,
  type SharePoolNew,
  Factions,
  type WarShipModel
} from '@/coreModel/types'
import { shareTable } from '@/coreModel/shareTable'
import _ from 'lodash'
import { fn_Guid } from '@/utils/uuidUtils'
import { useFleetFightViewStore } from '@/views/FleetFightViewNew/store/fleetFightViewStore'
import {
  CarilionReconModel,
  Cas066IntegratedModel,
  Eris1HeavyCannonModel,
  TaurusPulseCannonModel,
  WingedHussarAntiShipModel,
  convertWeaponModelIdToWeaponName,
  convertShipModelIdToShipModelName,
  shipModelList,
  findShipModelById
} from '@/coreModel/shipConfig'

const fleetTemplate = [
  { warshipModel: TaurusPulseCannonModel, count: 3 },
  { warshipModel: Eris1HeavyCannonModel, count: 3 },
  { warshipModel: WingedHussarAntiShipModel, count: 5 },
  { warshipModel: CarilionReconModel, count: 5 },
  { warshipModel: Cas066IntegratedModel, count: 2 }
]

export const useFleetNewStore = defineStore('fleetNew', () => {
  const fleetFightViewStore = useFleetFightViewStore()

  const ourFleet = ref<ModelFleet>({ id: fn_Guid(), shipList: [] })
  const enemyFleet = ref<ModelFleet>({ id: fn_Guid(), shipList: [] })
  ourFleet.value.shipList.splice(0, 0, ...fleetTemplate) // 插入mock数据
  enemyFleet.value.shipList.splice(0, 0, ...fleetTemplate) // 插入mock数据

  // 我方舰队所有武器的分摊池
  const ourFleetSharePoolList = computed<SharePoolNew[]>(() => {
    const sharePoolList: SharePoolNew[] = []
    // 遍历整个舰队的所有武器
    ourFleet.value.shipList.forEach((shipGroup) => {
      shipGroup.warshipModel.weaponList.forEach((weaponModel) => {
        sharePoolList.push(CalculateWeaponShareNew(weaponModel, enemyFleet.value))
      })
    })
    return sharePoolList
  })
  // 当前选中的舰船的武器可攻击目标计算（也就是当前选中的舰船的武器分摊池）
  const ourSelectedShipSharePool = computed<SharePoolNew[] | undefined>(() => {
    if (
      fleetFightViewStore.selectedShip &&
      fleetFightViewStore.selectedShip.factions == Factions.Our
    ) {
      return queryAttackableTargetByShipModelId(
        fleetFightViewStore.selectedShip?.id,
        ourFleet.value,
        ourFleetSharePoolList.value
      )
    }
    return undefined
  })
  /**
   * 向舰队中添加舰船
   * @param shipModel 舰船型号
   * @param count 数量
   * @param factions 向敌方舰队添加还是向我方舰队添加
   * @returns
   */
  const addShipToFleet = (shipModel: WarShipModel, count: number, factions: Factions) => {
    const fleet = factions == Factions.Our ? ourFleet : enemyFleet
    // 遍历整个我方舰队，查看当前是否已有这个型号
    for (let index = 0; index < fleet.value.shipList.length; index++) {
      // 如果有这个型号，直接添加count即可
      if (fleet.value.shipList[index].warshipModel.id == shipModel.id) {
        fleet.value.shipList[index].count += count
        return
      }
    }
    // 如果没有这个型号，则新建一个舰船组添加进去
    fleet.value.shipList.push({ warshipModel: shipModel, count: count })
    return
  }
  /**
   * 删除舰船型号
   * @param shipModel 船只型号
   * @param count 删除的数量
   * @param factions 从己方舰队删除还是从敌方舰队删除
   * @param isDeleteAll 是否删除全部这种型号的舰船（如果此项为true，则count参数无效）
   */
  const deleteShipFromFleet = (
    shipModel: WarShipModel,
    count: number,
    factions: Factions,
    isDeleteAll?: boolean
  ) => {
    const fleet = factions == Factions.Our ? ourFleet : enemyFleet
    // 遍历整个我方舰队，查看当前是否已有这个型号
    for (let index = 0; index < fleet.value.shipList.length; index++) {
      // 如果有这个型号，则执行删除
      if (fleet.value.shipList[index].warshipModel.id == shipModel.id) {
        // 检查这次删除是不是一下子删干净了所有这个型号的舰船
        if (fleet.value.shipList[index].count - count <= 0 || isDeleteAll) {
          fleet.value.shipList.splice(index, 1)
        } else {
          fleet.value.shipList[index].count -= count
        }
      }
    }
    // 如果没有这个型号的舰船，则什么都不做
    return
  }
  return {
    ourFleet,
    enemyFleet,
    ourFleetSharePoolList,
    ourSelectedShipSharePool,
    addShipToFleet,
    deleteShipFromFleet
  }
})

/**
 * 计算武器分摊池的函数
 * @param weaponModel 武器型号
 * @param modelFleet 敌方舰队（以 “船只型号 - 条数” 形式记录的 “舰队”）
 * @returns 这个武器的分摊池
 */
export function CalculateWeaponShareNew(
  weaponModel: WeaopnModel,
  modelFleet: ModelFleet
): SharePoolNew {
  // STEP1 按照武器射击模式进行过滤
  // （如果是直射，过滤掉对手中后排所有舰船）
  let tempShipList: ModelShipGroup[] = modelFleet.shipList
  if (weaponModel.shootMode == ShootMode.DirectFire) {
    tempShipList = modelFleet.shipList.filter((item) => {
      return item.warshipModel.shipTemplate.standRow == Row.Front
    })
  }
  // STEP2 设定武器锁定序列
  // STEP2.1 遍历经过上一步过滤的剩余敌方船只，找出敌方舰队中存在的，你武器锁定优先级最高级的那类船只，作为筛选条件
  let hightestAttackShipType: ShipType = ShipType.Frigate // 最高优先级的船只
  tempShipList.forEach((shipGroup) => {
    // STEP1 计算得出当前 “hightestAttackShipType” 变量在本武器中，锁定排名是多少
    const nowHightestAttackShipTypeRank = shipTypeToWeaponAttackRank(
      weaponModel,
      hightestAttackShipType
    )
    // STEP2 计算当前遍历到的这条敌方舰船在本武器的锁定序列中，的锁定排名
    const shipRank = shipTypeToWeaponAttackRank(
      weaponModel,
      shipGroup.warshipModel.shipTemplate.shipType
    )
    if (shipRank < nowHightestAttackShipTypeRank) {
      hightestAttackShipType = shipGroup.warshipModel.shipTemplate.shipType
    }
  })
  // STEP2.2 过滤敌方舰队，只剩下最高锁定优先级的那个种类的船只（比如：攻击序列优先级最高的是驱逐，过滤全部066，卡里莱恩）
  tempShipList = tempShipList.filter(
    (shipGroup) => shipGroup.warshipModel.shipTemplate.shipType == hightestAttackShipType
  )
  // STEP3 计算有几条船承接伤害（剩余舰船是阋神星*3 和斗牛*3，是6分2）
  const shareNumber = shareTable.get(tempShipList.length)
  return {
    id: fn_Guid(),
    weaponModelId: weaponModel.id,
    shareNumber: shareNumber ? shareNumber : 0,
    shipList: tempShipList
  }
}

/**
 * 输入“武器”与“舰船类型”，输出“这个舰船类型在这个武器的攻击序列中的排名”
 * @param weaponModel 武器
 * @param shipType 舰船类型
 * @returns 这个舰船类型在这个武器的攻击序列中的排名
 */
function shipTypeToWeaponAttackRank(weaponModel: WeaopnModel, shipType: ShipType) {
  return weaponModel.attackSequence.findIndex((item) => item == shipType)
}
/**
 * 输入 “当前选中的己方的舰船型号” 和 “当前己方舰队分摊池”，输出 “当前选中舰船型号能攻击的所有敌方舰船型号”
 * @param id 当前选中的舰船型号的id
 * @param fleet 舰队
 * @param sharePoolList 分摊池
 */
function queryAttackableTargetByShipModelId(
  id: string,
  fleet: ModelFleet,
  sharePoolList: SharePoolNew[]
) {
  // STEP1 找出 “当前选中的己方的舰船型号” 的所有武器列表
  const weaponList = fleet.shipList.find((shipGroup) => {
    return shipGroup.warshipModel.id == id
  })?.warshipModel.weaponList
  // STEP2 根据武器列表查询对应武器的分摊池
  if (weaponList) {
    const resultSharePoolList: SharePoolNew[] = []
    weaponList.forEach((weaponModel) => {
      console.log(weaponModel.id)
      const findedSharePool = sharePoolList.find((sharePool) => {
        return sharePool.weaponModelId == weaponModel.id
      })
      if (findedSharePool) {
        resultSharePoolList.push(findedSharePool)
      }
    })
    return resultSharePoolList
  }
  return undefined
}
